<script setup lang="ts">
import {ElMessage, ElMessageBox} from "element-plus";
import {logoutApi} from "@/api/client/user.ts";
import {removeClientToken} from "@/utils/token.ts";
import router from "@/router";
import {onMounted} from "vue";
import {useUserInfoStore} from "@/stores/client/user-info.ts";

let userInfoStore = useUserInfoStore();
onMounted(function () {
  userInfoStore.init()
})

async function logout() {
  ElMessageBox.confirm(
      '你确定退出登录吗?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        try {
          await logoutApi()
          removeClientToken()
          await router.push('/client/password-login')
        } catch (e: any) {
          ElMessage.warning(e)
        }
      })
}

async function goUserInfo() {
  await router.push('/client/user')
}
</script>

<template>
  <div>
    <div class="content">
      <el-dropdown placement="bottom-end" trigger="click" size="large">
        <div class="user-info">
          <el-text truncated style="font-size: 20px">{{userInfoStore.username}}</el-text>
          <el-avatar :src="userInfoStore.avatar"/>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="goUserInfo">个人信息</el-dropdown-item>
            <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<style scoped lang="scss">
.content {
  display: flex;
  align-items: center;
  width: 100px;
  :deep(.el-dropdown) {
    .user-info {
      display: flex;
      align-items: center;

      .el-text {
        margin-right: 20px;
        max-width: 100px;
        font-weight: bold;
        font-size: large;
      }
    }

    .user-info:hover {
      cursor: pointer;
    }
  }
}
</style>